import { TetrisGame } from './core/TetrisGame';
import { GameRenderer } from './renderers/GameRenderer';
import '../public/styles.css';

/**
 * 游戏入口
 */
function initGame(): void {
    const canvas = document.getElementById('gameCanvas') as HTMLCanvasElement;
    const nextCanvas = document.getElementById('nextCanvas') as HTMLCanvasElement;

    if (!canvas) {
        console.error('Canvas element not found');
        return;
    }

    // 创建游戏实例
    const game = new TetrisGame(canvas);

    // 设置下一个方块预览canvas
    if (nextCanvas) {
        nextCanvas.width = 100;
        nextCanvas.height = 100;
        const nextRenderer = new GameRenderer(nextCanvas, 20);

        // 定期更新下一个方块预览
        const updateNextPreview = () => {
            const nextTetromino = game.getNextTetromino();
            if (nextTetromino) {
                nextRenderer.clear();
                nextRenderer.drawNextTetromino(nextTetromino, 10, 10, 20);
            }
            requestAnimationFrame(updateNextPreview);
        };
        updateNextPreview();
    }

    // 更新分数显示
    const scoreElement = document.getElementById('score');
    const linesElement = document.getElementById('lines');
    const levelElement = document.getElementById('level');

    const updateInfo = () => {
        const scoreManager = game.getScoreManager();
        const score = scoreManager.getScore();
        const lines = scoreManager.getLines();
        const level = scoreManager.getLevel();

        if (scoreElement) scoreElement.textContent = `分数: ${score}`;
        if (linesElement) linesElement.textContent = `行数: ${lines}`;
        if (levelElement) levelElement.textContent = `等级: ${level}`;

        requestAnimationFrame(updateInfo);
    };
    updateInfo();

    // 添加开始按钮事件
    const startButton = document.getElementById('startButton');
    if (startButton) {
        startButton.addEventListener('click', () => {
            game.start();
        });
    }

    // 添加暂停按钮事件
    const pauseButton = document.getElementById('pauseButton');
    if (pauseButton) {
        pauseButton.addEventListener('click', () => {
            game.pause();
        });
    }

    // 添加重置按钮事件
    const resetButton = document.getElementById('resetButton');
    if (resetButton) {
        resetButton.addEventListener('click', () => {
            game.reset();
            game.start();
        });
    }

    // 页面卸载时清理
    window.addEventListener('beforeunload', () => {
        game.destroy();
    });
}

// 等待DOM加载完成
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initGame);
} else {
    initGame();
}

